﻿/*----------------------------------------------------------------
 * 
 * 版权所有：同程网络科技股份有限公司 Copyright (C) 2013
 * 
 * 文件名：FTPHelper.cs
 * 文件功能描述：
 * 
 * 
 * 作 者：张强5374
 * 邮 箱：zq5374@17u.cn
 * 日 期：2013-07-15 13:33:15
 * 
 * 
 * 修改标识： Author
 * 修改描述： 相关描述
 * 
 * ---------------------------------------------------------------- */

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace FunnyFace.Common
{
    public class FTPHelper
    {

        public string FTPServerIP { get; set; }

        public string FTPRemotePath { get; set; }

        public string FTPUserID { get; set; }

        public string FTPPassword { get; set; }

        public string FTPURI { get; private set; }

        /// <summary>   
        /// 连接FTP   
        /// </summary>   
        /// <param name="FtpServerIP">FTP连接地址</param>   
        /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>   
        /// <param name="FtpUserID">用户名</param>   
        /// <param name="FtpPassword">密码</param>   
        public FTPHelper(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
        {
            FTPServerIP = FtpServerIP;
            FTPRemotePath = FtpRemotePath;
            FTPUserID = FtpUserID;
            FTPPassword = FtpPassword;
            FTPURI = "ftp://" + FTPServerIP + "/";
            if (!string.IsNullOrEmpty(FTPRemotePath))
            {
                FTPURI += FTPRemotePath + "/";
            }
        }


        /// <summary>   
        /// 上传   
        /// </summary>   
        /// <param name="filename"></param>   
        public void Upload(string filename)
        {
            FileInfo fileInf = new FileInfo(filename);
            string uri = FTPURI + fileInf.Name;
            FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(uri));
            reqFTP.Credentials = new NetworkCredential(FTPUserID, FTPPassword);
            reqFTP.KeepAlive = false;
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.UseBinary = true;
            reqFTP.ContentLength = fileInf.Length;
            const int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            FileStream fs = fileInf.OpenRead();
            try
            {
                Stream strm = reqFTP.GetRequestStream();
                int contentLen = fs.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                strm.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
            }
        }
        /// <summary>   
        /// 下载   
        /// </summary>   
        /// <param name="filePath"></param>   
        /// <param name="fileName"></param>   
        public void Download(string filePath, string fileName)
        {
            try
            {
                using (FileStream outputStream = new FileStream(filePath + "//" + fileName, FileMode.Create))
                {
                    FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(FTPURI + fileName));
                    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                    reqFTP.UseBinary = true;
                    reqFTP.Credentials = new NetworkCredential(FTPUserID, FTPPassword);
                    using (FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse())
                    {
                        using (Stream ftpStream = response.GetResponseStream())
                        {
                            long cl = response.ContentLength;
                            const int bufferSize = 2048;
                            byte[] buffer = new byte[bufferSize];
                            if (ftpStream != null)
                            {
                                int readCount = ftpStream.Read(buffer, 0, bufferSize);
                                while (readCount > 0)
                                {
                                    outputStream.Write(buffer, 0, readCount);
                                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                                }
                            }
                        }
                    }

                }

            }
            catch (Exception ex)
            {
                throw;
            }
        }


        /// <summary>   
        /// 删除文件   
        /// </summary>   
        /// <param name="fileName"></param>   
        public void Delete(string fileName)
        {
            try
            {
                string uri = FTPURI + fileName;
                FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(uri));
                reqFTP.Credentials = new NetworkCredential(FTPUserID, FTPPassword);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                if (datastream != null)
                {
                    StreamReader sr = new StreamReader(datastream);
                    sr.ReadToEnd();
                    sr.Close();
                    datastream.Close();
                }

                response.Close();
            }
            catch (Exception ex)
            {
            }
        }


        /// <summary>   
        /// 获取当前目录下明细(包含文件和文件夹)   
        /// </summary>   
        /// <returns></returns>   
        public IList<string> GetFilesDetailList()
        {
            try
            {
                IList<string> result = new List<string>();
                FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(new Uri(FTPURI));
                ftp.Credentials = new NetworkCredential(FTPUserID, FTPPassword);
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = ftp.GetResponse();
                Stream stream = response.GetResponseStream();
                if (stream != null)
                {
                    StreamReader reader = new StreamReader(stream);
                    string line = reader.ReadLine();
                    line = reader.ReadLine();
                    line = reader.ReadLine();
                    while (line != null)
                    {
                        result.Add(line);
                        line = reader.ReadLine();
                    }

                    reader.Close();
                    stream.Close();
                    response.Close();
                }
                return result;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>   
        /// 获取FTP文件列表包括文件夹   
        /// </summary>   
        /// <returns></returns>   
        private string[] GetAllList(string url, string userid, string password)
        {
            List<string> list = new List<string>();
            FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(url));
            req.Credentials = new NetworkCredential(userid, password);
            req.Method = WebRequestMethods.Ftp.ListDirectory;
            req.UseBinary = true;
            req.UsePassive = true;
            try
            {
                using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
                {
                    Stream stream = res.GetResponseStream();
                    if (stream != null)
                    {
                        using (StreamReader sr = new StreamReader(stream))
                        {
                            string s;
                            while ((s = sr.ReadLine()) != null)
                            {
                                list.Add(s);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return list.ToArray();
        }


        /// <summary>   
        /// 获取当前目录下文件列表 不包括文件夹   
        /// </summary>   
        /// <returns></returns>   
        public string[] GetFileList(string url, string userid, string password)
        {

            StringBuilder result = new StringBuilder();
            try
            {
                FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(url));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(userid, password);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = reqFTP.GetResponse();
                Stream stream = response.GetResponseStream();
                if (stream != null)
                {
                    StreamReader reader = new StreamReader(stream);
                    string line = reader.ReadLine();
                    while (line != null)
                    {

                        if (line.IndexOf("<DIR>", System.StringComparison.Ordinal) == -1)
                        {
                            result.Append(Regex.Match(line, @"[/S]+ [/S]+", RegexOptions.IgnoreCase).Value.Split(' ')[1]);
                            result.Append("/n");
                        }
                        line = reader.ReadLine();
                    }
                    result.Remove(result.ToString().LastIndexOf("/n", System.StringComparison.Ordinal), 1);
                    reader.Close();
                }
                response.Close();
            }
            catch (Exception ex)
            {
                throw;
            }
            return result.ToString().Split(Convert.ToChar("/n"));
        }

        /// <summary>   
        /// 判断当前目录下指定的子目录是否存在   
        /// </summary>   
        /// <param name="RemoteDirectoryName">指定的目录名</param>   
        public bool DirectoryExist(string RemoteDirectoryName)
        {
            IEnumerable<string> dirList = GetDirectoryList();
            return dirList.Any(str => str.Trim() == RemoteDirectoryName.Trim());
        }

        private IEnumerable<string> GetDirectoryList()
        {
            throw new NotImplementedException();
        }

        /// <summary>   
        /// 判断当前目录下指定的文件是否存在   
        /// </summary>   
        /// <param name="RemoteFileName">远程文件名</param>   
        public bool FileExist(string RemoteFileName)
        {
            IEnumerable<string> fileList = GetFileList("*.*");
            return fileList.Any(str => str.Trim() == RemoteFileName.Trim());
        }

        private IEnumerable<string> GetFileList(string p)
        {
            throw new NotImplementedException();
        }
        /// <summary>   
        /// 创建文件夹   
        /// </summary>   
        /// <param name="dirName"></param>   
        public void MakeDir(string dirName)
        {
            try
            {
                // dirName = name of the directory to create.   
                FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(FTPURI + dirName));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(FTPUserID, FTPPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                if (ftpStream != null)
                {
                    ftpStream.Close();
                }
                response.Close();
            }
            catch (Exception ex)
            {
            }
        }
        /// <summary>   
        /// 获取指定文件大小   
        /// </summary>   
        /// <param name="filename"></param>   
        /// <returns></returns>   
        public long GetFileSize(string filename)
        {
            long fileSize = 0;
            try
            {
                FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(FTPURI + filename));
                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(FTPUserID, FTPPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                fileSize = response.ContentLength;
                if (ftpStream != null)
                {
                    ftpStream.Close();
                }
                response.Close();
            }
            catch (Exception ex)
            {
            }
            return fileSize;
        }


        /// <summary>   
        /// 改名   
        /// </summary>   
        /// <param name="currentFilename"></param>   
        /// <param name="newFilename"></param>   
        public void ReName(string currentFilename, string newFilename)
        {
            try
            {
                FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(FTPURI + currentFilename));
                reqFTP.Method = WebRequestMethods.Ftp.Rename;
                reqFTP.RenameTo = newFilename;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(FTPUserID, FTPPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                if (ftpStream != null)
                {
                    ftpStream.Close();
                }
                response.Close();
            }
            catch (Exception ex)
            {
            }
        }

        /// <summary>   
        /// 移动文件   
        /// </summary>   
        /// <param name="currentFilename"></param>   
        /// <param name="newDirectory"></param>   
        public void MovieFile(string currentFilename, string newDirectory)
        {
            ReName(currentFilename, newDirectory);
        }

        /// <summary>   
        /// 切换当前目录   
        /// </summary>   
        /// <param name="DirectoryName"></param>   
        /// <param name="IsRoot">true 绝对路径   false 相对路径</param>    
        public void GotoDirectory(string DirectoryName, bool IsRoot)
        {
            if (IsRoot)
            {
                FTPRemotePath = DirectoryName;
            }
            else
            {
                FTPRemotePath += DirectoryName + "/";
            }
            FTPURI = "ftp://" + FTPServerIP + "/" + FTPRemotePath + "/";
        }
    }
}